package top.dancun.easuser.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.dancun.common.entity.RoleEntity;
import top.dancun.common.utils.PageUtils;
import top.dancun.common.utils.R;
import top.dancun.easuser.entity.UserRoleEntity;
import top.dancun.easuser.service.RoleService;
import top.dancun.easuser.service.UserRoleService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;



/**
 * 
 *
 * @author dancun
 * @email message@dancun.top
 * @date 2022-09-05 22:15:48
 */
@RestController
@RequestMapping("/userrole")
public class UserRoleController extends AbstractController{
    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("easuser:userrole:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userRoleService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("easuser:userrole:info")
    public R info(@PathVariable("id") Long id){
		UserRoleEntity userRole = userRoleService.getById(id);

        return R.ok().put("userRole", userRole);
    }
//临时使用，后续记得写入service
    @RequestMapping("/myroles")
    public R listMyRoles(){
        String uid = getUserId();
        List<UserRoleEntity> userRoles = userRoleService.lambdaQuery().eq(UserRoleEntity::getUserId,uid).list();
        List<Long> roleIds = new ArrayList<>();
        for(UserRoleEntity userRole :userRoles){
            roleIds.add(userRole.getRoleId());
        }
        List<RoleEntity> roleEntityList= roleService.lambdaQuery().in(RoleEntity::getRoleId,roleIds).list();

        return R.ok().put("data", roleEntityList);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("easuser:userrole:save")
    public R save(@RequestBody UserRoleEntity userRole){
		userRoleService.save(userRole);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("easuser:userrole:update")
    public R update(@RequestBody UserRoleEntity userRole){
		userRoleService.updateById(userRole);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("easuser:userrole:delete")
    public R delete(@RequestBody Long[] ids){
		userRoleService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
